package com.test.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.java.common.Result;
import com.test.java.common.ResultUtil;
import com.test.java.model.User;
import com.test.java.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description: 用于测试freemarker
 * @Author laoxu
 * @Date 2021/1/23 11:57
 **/
@Controller
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public String list(Model model, @RequestParam(value = "s_username",required = false) String s_username){
        QueryWrapper<User> queryWrapper = null;
        if(!StringUtils.isEmpty(s_username)){
            queryWrapper = new QueryWrapper<>();
            queryWrapper.like("username", s_username);
        }
        List<User> userList = userService.list(queryWrapper);
        model.addAttribute("userList", userList);
        return "users";
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model){
        User user = userService.getById(id);
        if(user==null){
            user = new User();
        }

        model.addAttribute("user", user);
        return "userEdit";
    }

    @PostMapping("/remove/{id}")
    @ResponseBody
    public Result<String> remove(@PathVariable Integer id){
        userService.removeById(id);

        return ResultUtil.ok();
    }

    @PostMapping("save")
    public String save(User user){
        userService.saveOrUpdate(user);

        return "redirect:/users/list";
    }

}
